package Controllers;

import DB.DBLocation;
import DB.DBRoute;
import Models.Location;
import Models.Route;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

public class RouteController implements ControllerInterface<Route>
{ 
	public RouteController ()
	{}

	public int insert(Route route)
	{
		DBRoute dbr = new DBRoute();
		int routeNo = dbr.insert(route.exportData());

		route.setRouteNo(routeNo);
		route.setRouteNoOnLocations();
		insertDependent(route.getLocations());

		return routeNo;
	}

	public void insertDependent(ArrayList<? extends DB.RowInterface> data)
	{
		DBLocation dbl = new DBLocation();
		ArrayList<HashMap> rowsData = new ArrayList<HashMap>();
		Iterator<Location> i = ((ArrayList<Location>)data).iterator();
		while(i.hasNext())
		{
			Location location = i.next();
			if(dbl.alreadyExists(location.getLocationNo()))
			{
				dbl.update(location.exportData(), "locationNo = "+location.getLocationNo());
			}
			else
			{
				rowsData.add(location.exportData());
			}
		}
		dbl.insert(rowsData);
	}

	public Route find(int id)
	{
		DBRoute dbr = new DBRoute();
		return dbr.fetchByNo(id);
	}

	public int update(Route route, String where)
	{
		updateDependent(route.getLocations(), null);

		return 1;
	}

	public void updateDependent(ArrayList<? extends DB.RowInterface> data, String where)
	{
		DBLocation dbl = new DBLocation();
		Iterator<Location> i = ((ArrayList<Location>)data).iterator();
		while(i.hasNext())
		{
			Location location = i.next();
			if(dbl.alreadyExists(location.getLocationNo()))
			{
				dbl.update(location.exportData(), "locationNo = "+location.getLocationNo());
			}
			else
			{
				dbl.insert(location.exportData());
			}
		}
	}

	public int delete(int id)
	{
		DBRoute dbr = new DBRoute();
		return dbr.deleteByNo(id);
	}

	public ArrayList<Route> fetchAll()
	{
		DBRoute dbr = new DBRoute();
		return dbr.fetchAll();
	}
}